import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";

import { COOKIE_ACCESS_TOKEN } from "./lib/constants";

const PUBLIC_PATHS = ["/auth/login", "/api/auth", "/_next", "/favicon", "/assets"];

function isPublicPath(pathname: string) {
  return PUBLIC_PATHS.some((publicPath) => pathname.startsWith(publicPath));
}

export function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;

  if (isPublicPath(pathname)) {
    return NextResponse.next();
  }

  const token = request.cookies.get(COOKIE_ACCESS_TOKEN)?.value;

  if (!token) {
    const loginUrl = new URL("/auth/login", request.url);
    if (pathname !== "/") {
      loginUrl.searchParams.set("from", pathname);
    }
    return NextResponse.redirect(loginUrl);
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/dashboard/:path*", "/schedule/:path*", "/reports/:path*"],
};
